//
//  OTTexture.m
//  LuPingBox
//
//  Created by 茶 on 2023/11/10.
//  Copyright © 2023 DD. All rights reserved.
//

#import "CATexture.h"
#import <GLKit/GLKit.h>
#import <OpenGLES/ES3/glext.h>

@implementation CATexture

- (instancetype)init
{
    self = [super init];
    if (self) {
        glActiveTexture(GL_TEXTURE0);
        glGenTextures(1, &_originalTexture);
        glBindTexture(GL_TEXTURE_2D, _originalTexture);
    }
    return self;
}

- (void)setupTexture:(CVPixelBufferRef)pixelBuffer {
    CVPixelBufferLockBaseAddress(pixelBuffer, 0);
    glActiveTexture(GL_TEXTURE0);
    GLsizei width = (GLsizei)CVPixelBufferGetWidth(pixelBuffer);
    GLsizei height = (GLsizei)CVPixelBufferGetHeight(pixelBuffer);
    GLsizei bytesPerRow = (GLsizei)CVPixelBufferGetBytesPerRow(pixelBuffer);
    glBindTexture(GL_TEXTURE_2D, _originalTexture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bytesPerRow / 4, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, CVPixelBufferGetBaseAddress(pixelBuffer));
    
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    self.width = width;
    self.height = height;
    
    CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
    CVPixelBufferRelease(pixelBuffer);

}
@end
